# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 京东滑块.py
"""

'''
selenium 
pyppeteer   过滑块
'''
from urllib import request
from pyppeteer import launch
import asyncio
import random
import cv2

# 缺口识别  采用 cv2

async  def get_track():
    img = cv2.imread('image.png',0)
    template = cv2.imread('template.png',0)
    # 归一化算法
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    value = cv2.minMaxLoc(res)[2][0]
    distance = value * 278 / 360
    return distance

async  def main():
    browser = await launch({
        'headless':False,
        'args':['--window-size=1366,768'],
    })
    # 设置边距
    page = await browser.newPage()

    await page.setViewport({'width':1366,"height":768})

    await page.goto('https://passport.jd.com/new/login.aspx')

    await page.click('div.login-tab-r')

    # 输入用户名  密码  点击登录
    await page.type('#loginname','12345678@qq.com',{
        'delay':random.randint(60,130)
    })

    await page.type('#nloginpwd','1231231232',{
        'delay': random.randint(60, 130)
    })

    await page.waitFor(2000)
    # 点击登录
    await page.click('div.login-btn')
    await page.waitFor(2000)

    # 定位图片
    image_src = await page.Jeval('.JDJRV-bigimg >img', 'el => el.src')
    template_src = await page.Jeval('.JDJRV-smallimg >img', 'el => el.src')
    # 图片地址   图片名称
    request.urlretrieve(image_src,'image.png')
    request.urlretrieve(template_src,'template.png')

    # 识别缺口
    distabce = await get_track()

    # 拖动
    el  = await page.J('div.JDJRV-slide-btn')
    box = await el.boundingBox()
    await page.hover('div.JDJRV-slide-btn')

    # 按下鼠标
    await page.mouse.down()
    await page.mouse.move(box['x'] + distabce +random.uniform(30,33), box['y'], {'steps':30})
    await page.waitFor(random.randint(300,600))
    await page.mouse.move(box['x'] +distabce + 29,box['y'], {'steps':30})
    await page.mouse.up()  # 放开鼠标
    await page.waitFor(2000)

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())

